package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.service.FileUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * ClassName: FileUploadServiceImpl
 * Package: com.atguigu.gmall.product.service.impl
 * Description:
 *
 * @Author 刘轩
 * @Create 2023-08-19 16:55
 * @Version 1.0
 */

@Service
@RefreshScope
public class FileUploadServiceImpl implements FileUploadService {
    //  这种读取数据方式叫软编码！
    @Value("${minio.endpointUrl}")
    private String endpointUrl; // endpointUrl = http://192.168.200.130:9000
    @Value("${minio.bucketName}")
    private String bucketName;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secreKey}")
    private String secreKey;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @Override
    public Result uploadFile(MultipartFile file) {

        // 文件上传之后，需要回显
        //  返回数据--上传之后的文件路径
        String url = "";
        try {
            // 创建minioClient 客户端

            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(endpointUrl)
                            .credentials(accessKey, secreKey)
                            .build();

            // 判断桶是否存在。
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (!found) {
                // 如果不存在，则创建
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            } else {
                //  这个桶已经存在.
                System.out.println("Bucket " + bucketName + " already exists.");
            }
            // 文件名不能重复，同时还需要添加后缀名
            String fileName = System.currentTimeMillis() + UUID.randomUUID().toString().replaceAll("-", "") + "." + FilenameUtils.getExtension(file.getOriginalFilename());
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                            file.getInputStream(), file.getSize(), -1
                    ).contentType(file.getContentType()).build());
            // 回显内容
            url = endpointUrl + "/" + bucketName + "/" + fileName;
        } catch (MinioException e) {
            System.out.println("Error occurred:" + e);
            System.out.println("HTTP trace" + e.httpTrace());
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
        //
        return Result.ok(url);
    }

}

